package com.mengxinya.ys.task;

import com.mengxinya.ys.config.AppConfigService;
import com.mengxinya.ys.sdk.ServerDetail;
import com.mengxinya.ys.sdk.ServerManager;
import com.mengxinya.ys.sdk.ServerSdkException;
import com.mengxinya.ys.sdk.ServerState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 自动关闭服务器任务
 */
@Component
@Slf4j
public class AutoCloseServerTask {

    private final ServerManager serverManager;

    private final AppConfigService appConfigService;

    public AutoCloseServerTask(ServerManager serverManager, AppConfigService appConfigService) {
        this.serverManager = serverManager;
        this.appConfigService = appConfigService;
    }

    /**
     * 每天凌晨1点执行关闭服务器任务
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void closeServer() {
        doCLoseServer();
    }

    private void doCLoseServer() {
        ServerDetail tiziServer = appConfigService.getTiziServerDetail();
        try {
            ServerState serverState = serverManager.getServerState(tiziServer);
            if (serverState.getServerState().equals(ServerState.RUNNING)) {
                log.info("Tizi server is running, stop it");
                serverManager.stopServerInstance(tiziServer);
            }

        } catch (ServerSdkException e) {
            log.error(e.getLocalizedMessage(), e);
        }
    }
}
